package core;

import java.io.*;
import java.net.*;


public class ClientReceiver extends Thread {

    private static boolean isRunning = false;
    private static boolean isEnd = false;
    private static int ReceivePort = 4446;
    private static int SendPort = 4447;
    public void run()
    {
        String machineName = null;
        try {    
            InetAddress addr = InetAddress.getLocalHost();
            machineName = addr.getHostName();
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
            machineName = "unknown";
        }   
        byte [] buf = new byte[10];
        byte[] SendBuf = machineName.getBytes();
        DatagramPacket packetRecv = null;
        DatagramPacket packetSend = null;
        DatagramSocket datagramSocketRecv, datagramSocketSend;
        try {
            datagramSocketRecv = new DatagramSocket(ReceivePort);
            datagramSocketSend = new DatagramSocket(SendPort);
            datagramSocketRecv.setSoTimeout(1000);
        }
        catch (SocketException ex)
        {
            ex.printStackTrace();
            return;
        }

        isRunning = true;
        while (isRunning)
        {
            try{
                packetRecv = new DatagramPacket(buf, buf.length);
                datagramSocketRecv.receive(packetRecv);

            } catch (IOException ex) {
                ex.printStackTrace();
                continue;
            }
            InetAddress addr = packetRecv.getAddress();
            System.out.println("Recv from " + addr.getHostAddress());
            packetSend = new DatagramPacket(SendBuf, SendBuf.length, addr, SendPort);
            try {
                datagramSocketSend.send(packetSend);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        datagramSocketRecv.close();
        datagramSocketSend.close();
        isEnd = true;
    }
    public void stopThread()
    {
        isRunning = false;
        while (!isEnd)
        {            
            try {
                Thread.sleep(50);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

}
